﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Orchid.Blazor.Hosting.Repositories
{
    /// <summary>
    /// 网站仓库。
    /// </summary>
    public abstract class WebRepository : MarshalByRefObject, IFileProvider, IDisposable
    {
        /// <summary>
        /// 内容目录名。
        /// </summary>
        public const string ContentDirectoryName = "wwwroot";
        /// <summary>
        /// 默认文件名。
        /// </summary>
        public const string DefaultFileName = "index.html";

        /// <summary>
        /// 重写规则。
        /// </summary>
        protected IDictionary<string, Func<Stream, Stream>> RewriteRules { get; } = new Dictionary<string, Func<Stream, Stream>>(StringComparer.OrdinalIgnoreCase);

        /// <summary>
        /// 名称。
        /// </summary>
        public abstract string Name { get; }
        /// <summary>
        /// 路径。
        /// </summary>
        public virtual string Path { protected set; get; }

        /// <summary>
        /// <inheritdoc cref="WebRepository"/>
        /// </summary>
        public WebRepository()
        {
            this.RewriteRules[$"/{DefaultFileName}"] = this.OnRewriteIndexHtml;
        }

        /// <summary>
        /// 获取目录。
        /// </summary>
        /// <param name="subpath">路径。</param>
        /// <returns>获取到的目录。</returns>
        public virtual IDirectoryContents GetDirectoryContents(string subpath) => NotFoundDirectoryContents.Singleton;
        /// <inheritdoc cref="GetFileInfo(string)"/>
        protected abstract IFileInfo GetFile(string subpath);
        /// <summary>
        /// 获取文件。
        /// </summary>
        /// <param name="subpath">路径。</param>
        /// <returns>获取到的文件。</returns>
        public virtual IFileInfo GetFileInfo(string subpath)
        {
            var file = this.GetFile(subpath);
            if (file == null) return file;
            if (!file.Exists) return file;
            if (this.RewriteRules.TryGetValue(subpath, out var rewriteRule)) return new WebRewriteFile(file, rewriteRule);
            return file;
        }
        /// <summary>
        /// 监控。
        /// </summary>
        /// <param name="filter">过滤器。</param>
        /// <returns>获取到的更改令牌。</returns>
        public virtual IChangeToken Watch(string filter) => NullChangeToken.Singleton;

        protected virtual Stream OnRewriteIndexHtml(Stream stream)
        {
            if (string.IsNullOrWhiteSpace(this.Name)) return stream;

            var content = new StreamReader(stream).ReadToEnd();
            content = content.Replace("<base href=\"/\" />", "<base href=\"/" + this.Name + "/\" />");

            var ms = new MemoryStream();
            var sw = new StreamWriter(ms);
            sw.Write(content);
            sw.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            return ms;
        }

        private RequestDelegate _executor = null;
        private object _executor_lock = new object();
        private IHost _host = null;
        /// <summary>
        /// 执行器。
        /// </summary>
        public RequestDelegate Executor
        {
            get
            {
                if (_executor == null) lock (_executor_lock) if (_executor == null) _executor = this.GetExecutor();
                return _executor;
            }
        }
        /// <summary>
        /// 获取执行器。
        /// </summary>
        /// <returns>获取到的执行器。</returns>
        protected virtual RequestDelegate GetExecutor()
        {
            RequestDelegate executor = null;
            void OnConfigureHostBuilder(IWebHostBuilder hostBuilder)
            {
                hostBuilder.ConfigureServices(services =>
                {
                    services.Where(x => x?.ServiceType == typeof(IServer)).ToList().ForEach(x => services.Remove(x));
                    services.AddSingleton<IServer, EmptyServer>();
                });
                hostBuilder.Configure(app =>
                {
                    var env = app.ApplicationServices.GetService<IWebHostEnvironment>();
                    env.WebRootFileProvider = this;
                    if (env.IsDevelopment())
                    {
                        app.UseDeveloperExceptionPage();
                        app.UseWebAssemblyDebugging();
                    }

                    app.UseBlazorFrameworkFiles();
                    app.UseStaticFiles();
                    app.UseRouting();
                    app.UseEndpoints(endpoints => endpoints.MapFallbackToFile(WebRepository.DefaultFileName));

                    executor = app.Build();
                });
            }
            _host = Host.CreateDefaultBuilder(Environment.GetCommandLineArgs().Skip(1).ToArray()).ConfigureWebHostDefaults(OnConfigureHostBuilder).Build();
            _host.Start();

            var logger = _host.Services.GetService<ILoggerFactory>().CreateLogger(this.GetType());
            logger?.LogInformation($"Name = {this.Name}\n      Path = {this.Path}");

            return executor;
        }

        /// <summary>
        /// 转换成字符串。
        /// </summary>
        /// <returns>转换得到的字符串。</returns>
        public override string ToString() => this.Name;

        /// <summary>
        /// 释放资源。
        /// </summary>
        public virtual void Dispose()
        {
            _host?.Dispose();
        }
    }

    class EmptyServer : IServer
    {
        public IFeatureCollection Features { get; }
        public Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken) where TContext : notnull => Task.CompletedTask;
        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
        public void Dispose() { }
    }
}
